<?php

namespace App\Http\Middleware;

use Closure;
use URL;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use App\Model\AdminUserModel;
use App\Model\AdminRoleUserModel;

//后台登陆 权限
class CheckAdminLogin {
  public function handle($request, Closure $next)
  {
    $url = url('admin/login');

    //验证是否登陆
    if(!session('admin_id')){
        echo "<script>alert('请重新登陆')</script>";
        echo "<script>top.location.href='{$url}'</script>";
        return ;
    }
    $id = session('admin_id');

    // $auModel = new AdminUserModel;//管理员表
    $res = AdminUserModel::where('id',$id)->first();//管理员信息
    if($res['state']['value'] != 1){
        echo "<script>alert('该用户已被冻结，请联系管理员进行激活')</script>";
        echo "<script>top.location.href='{$url}'</script>";
        return ;
    }

    view()->share('adminUser',$res['user']);

    // view()->share('toUrl', $request->path());

    //权限
    $previousUrl = URL::previous();//上一个路径
    $path = $request->path();//当前路径
    // dump($path);
    $method = $request->getMethod();//请求方式
    // dump($method);

    //默认权限
    $defArr = ['admin','admin/home','admin/admin/personal','admin/admin/personal/up','admin/upload','admin/shop_up','admin/logo_up','admin/label_up','admin/qrcode_up','admin/source_up','admin/source_ve','admin/shop_editor','admin/banner_up','admin/goods_up','admin/notice/upload','admin/banner/do_sort','admin/banner/sort','admin/shophome/index','admin/shophome/add','admin/shophome/insert','admin/shophome/edit','admin/shophome/update','admin/shophome/del','admin/shophome/update','admin/shophome/update_sort','admin/sku/edit_skupic','admin/sku/sku_edit','admin/sku/update_skupic','admin/shop/source_insert','admin/shop/sourcepic_add','admin/shop/source_del','admin/wish/send_ok_cy'];
    view()->share('nodeDefArr', $defArr);

    if(in_array($path,$defArr)){
        return $next($request);
    }

    //总管理员
    if($id == 1){
        return $next($request);
    }

    //权限
    $nodes = AdminRoleUserModel::from('admin_role_user as aru')
        ->join('admin_node_role as anr','aru.role_id','=','anr.role_id')
        ->join('admin_node as n','anr.node_id','=','n.id')
        ->where('aru.user_id',$id)
        ->pluck('n.name')
        ->toArray();
    // dump($nodes);die;

    if(!in_array($path,$nodes)){
        if($method == 'POST'){
            return returnJson(0,'没有权限');
            // return response()->json(['code'=>0,'msg'=>'没有权限']);
            // return  response()->json(403);
        }
        if($method == 'GET'){
            return response()->view('admin.403',compact('previousUrl'));
        }
    }

    return $next($request);
  }
  
}
